package server.util;

import server.Lifecycle;
import server.LifecycleEvent;
import server.LifecycleListener;
/*
生命周期工具,需要实现Lifecycle接口的类可以将该类的对象作为成员参数,
响应的生命周期操作调用该类对象的相关方法即可
*/

/*
2023/2/7 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public final class LifecycleSupport {
    private Lifecycle lifecycle = null;
    private LifecycleListener listeners[] = new LifecycleListener[0];

    public LifecycleSupport(Lifecycle lifecycle) {
        this.lifecycle = lifecycle;
    }

    //触发生命周期事件
    public void fireLifecycleEvent(String type, Object data) {
        LifecycleEvent event = new LifecycleEvent(lifecycle, type, data);
        LifecycleListener interested[] = null;
        synchronized (listeners) {
            interested = listeners.clone();
        }
        for (int i = 0; i < interested.length; i++)
            interested[i].lifecycleEvent(event);

    }


    public void addLifecycleListener(LifecycleListener listener) {
        synchronized (listeners) {
            LifecycleListener newListeners[] = new LifecycleListener[listeners.length + 1];
            for (int i = 0; i < listeners.length; i++)
                newListeners[i] = listeners[i];
            newListeners[listeners.length] = listener;
            listeners = newListeners;
        }
    }

    public LifecycleListener[] findLifecycleListeners() {
        return listeners;
    }

    public void removeLifecycleListener(LifecycleListener listener) {
        synchronized (listeners) {
            int n = -1;
            for (int i = 0; i < listeners.length; i++) {
                if (listeners[i] == listener) {
                    n = i;
                    break;
                }
            }
            if (n < 0)
                return;
            LifecycleListener newListeners[] = new LifecycleListener[listeners.length - 1];
            int j = 0;
            for (int i = 0; i < listeners.length; i++) {
                if (i != n)
                    newListeners[j++] = listeners[i];
            }
            listeners = newListeners;
        }

    }


}
